package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hh.timeselector.timeutil.datedialog.DateListener;
import com.hh.timeselector.timeutil.datedialog.TimeConfig;
import com.hh.timeselector.timeutil.datedialog.TimeSelectorDialog;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.ReWangGeFVO;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeWangGeHandleActivity extends BaseActivity implements View.OnClickListener {
    private EditText bh_change_wghandle;//编号
    private AutoCompleteTextView clbh_change_wghandle;//处理单位编号
    private EditText time_change_wghandle;//处理时间
    private ImageView time_img_change_wghandle;
    private EditText result_change_wghandle;
    private Button save_change_wghandle;//保存
    private Button cancle_change_wghandle;//取消
    private CustomApplication application;
    private Gson gson = new Gson();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Map<String, Object>> resultMap;
    public List<ReWangGeFVO> suggest;
    public ArrayAdapter<ReWangGeFVO> aAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    // TODO: 2017/5/21 修改null
                    //Intent intent = new Intent(ChangeWangGeHandleActivity.this, WangGeHandleActivity.class);

                    //startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_wang_ge_handle);
        init();
        application = (CustomApplication) getApplication();

        // TODO: 2017/5/21  根据ID查询后台数据
        Intent intent = getIntent();
        getWangGeInfo(intent.getStringExtra("sid"));
        //getWangGeInfo("1000030");
    }

    protected void init() {
        bh_change_wghandle = (EditText) findViewById(R.id.bh_change_wghandle);
        textMap.put("sid",bh_change_wghandle);
        clbh_change_wghandle = (AutoCompleteTextView) findViewById(R.id.clbh_change_wghandle);
        textMap.put("cldwid",clbh_change_wghandle);

        time_change_wghandle = (EditText) findViewById(R.id.time_change_wghandle);
        textMap.put("cltime",time_change_wghandle);

        time_img_change_wghandle = (ImageView) findViewById(R.id.time_img_change_wghandle);
        result_change_wghandle = (EditText) findViewById(R.id.result_change_wghandle);
        textMap.put("clresult",result_change_wghandle);

        save_change_wghandle = (Button) findViewById(R.id.save_change_wghandle);
        cancle_change_wghandle = (Button) findViewById(R.id.cancle_change_wghandle);
        time_img_change_wghandle.setOnClickListener(this);
        save_change_wghandle.setOnClickListener(this);
        cancle_change_wghandle.setOnClickListener(this);
        suggest = new ArrayList<ReWangGeFVO>();
        clbh_change_wghandle.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable editable) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new ChangeWangGeHandleActivity.getJson().execute(newText);
            }

        });
    }

    public void getWangGeInfo(final String sid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                Request request=null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            // TODO: 2017/5/21  String.valueOf(application.getLoginUser().getLogin_id())
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    request = new Request.Builder().url(ConfUtils.SERVICE_URL + "grid_event/handleUpdate/c_aj_sjcl-" + sid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (final Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));

                                    }
                                }
                            }
                        });

                    }else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } finally {
                    if(response!=null)response.close();

                }
            }
        }).start();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.time_img_change_wghandle:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String date = sdf.format(new Date());
                showDatePickDialog(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE, date);
                break;
            case R.id.save_change_wghandle:
                if ("".equals(bh_change_wghandle.getText().toString().trim())
                        || "".equals(clbh_change_wghandle.getText().toString().trim())
                        || "".equals(time_change_wghandle.getText().toString().trim()) // "".equals(((RegisterRolePirVO) dwid_chaneg_wg_sp.getSelectedItem()).getId())
                        ) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());
                                }
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_sjcl").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }else{
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();

                            }
                        }
                    }).start();
                   // Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    // TODO: 2017/5/21  null
                    //Intent intent2 = new Intent(ChangeWangGeHandleActivity.this, null);
                    //startActivity(intent2);
                    finish();
                }




                break;
            case R.id.cancle_change_wghandle:
                finish();
                break;
        }
    }

    private void showDatePickDialog(int type, String date) {
        TimeSelectorDialog dialog = new TimeSelectorDialog(this);
        //设置标题
        dialog.setTimeTitle("选择时间:");
        //显示类型
        dialog.setIsShowtype(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE);
        //默认时间
        dialog.setCurrentDate(date);
        //隐藏清除按钮
        dialog.setEmptyIsShow(false);
        dialog.setDateListener(new DateListener() {
            @Override
            public void onReturnDate(String time, int year, int month, int day, int hour, int minute, int isShowType) {
                time_change_wghandle.setText(time);
            }

            @Override
            public void onReturnDate(String empty) {
                time_change_wghandle.setText(empty);
            }
        });
        dialog.show();
    }

    class getJson extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            aAdapter = new ArrayAdapter<ReWangGeFVO>(getApplicationContext(), R.layout.simple_dropdown_item_1line, suggest);
            clbh_change_wghandle.setThreshold(1);
            clbh_change_wghandle.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        }

        @Override
        protected String doInBackground(String... key) {
            suggest.clear();
            Response response = null;
            if (key.length != 0 && !"".equals(key[0])) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "cldwid")
                            .add("code", "c_aj_sjcl")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .add("like", key.length == 0 ? "" : key[0])
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findLikeJson").post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        suggest = gson.fromJson(result, new TypeToken<List<ReWangGeFVO>>() {
                        }.getType());
                        System.out.println(suggest);
                    }
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
            }
            return null;
        }

    }
}
